/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2008 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */


#import <UIKit/UIKit.h>
#import "AccountView.h"
#import "UIController.h"
#import "FunambolAPI.h"
#import "base/util/StringBuffer.h"


@implementation AccountView

- (id)init {
    self = [super init];
	if (self)
	{
		// this title will appear in the navigation bar
		self.title = NSLocalizedString(@"Account",@"Account");
    }
    funBlue = [[UIColor alloc] initWithRed:0.0 green:0.4 blue:0.9 alpha:1.0];
	return self;
}

- (void) noCredsAlert: (NSString*) text{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Alert", @"Alert") message:text
                                                   delegate:self cancelButtonTitle:NSLocalizedString(@"OK", @"OK") otherButtonTitles: nil];
    [alert show];
    [alert release];   
}

- (void) loadView{
    UIView *contentView = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]];
	self.view = contentView;
	[contentView release];
	
	self.view.autoresizesSubviews = YES;
    
    small_font = [UIFont systemFontOfSize:15];
    
    accountTable = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStyleGrouped]; 
	accountTable.delegate = self;
    accountTable.dataSource = self;
    accountTable.scrollEnabled = NO;
	//accountTable.rowHeight = 60;
    [accountTable reloadData];
    
    [[FunambolAPI getInstance] loadSyncConfig:&URL username:&username password:&password];

  
    URLParameter = [[UITableViewCell alloc] init];
    [[URLParameter textLabel] setText:NSLocalizedString(@"Server",@"Server")];
    [URLParameter setSelectionStyle:UITableViewCellSelectionStyleNone];
    URLValue = [[UITextField alloc] initWithFrame:CGRectMake(116.0, 3.0, 185.0, 40 )];
    //URLValue = [[UITextField alloc] initWithFrame:CGRectMake(15.0, 3.0, 290, 40 )];
    URLValue.borderStyle = UITextBorderStyleNone;
    URLValue.font = small_font;
    URLValue.exclusiveTouch = YES;
    URLValue.autocorrectionType = UITextAutocorrectionTypeNo;
    if ([URL isEqualToString:@""]){
        URLValue.text = @"http://my.funambol.com/sync";
    }else{
        URLValue.text = URL;
    }
    URLValue.backgroundColor = [UIColor whiteColor];
    URLValue.keyboardType = UIKeyboardTypeURL;
    URLValue.returnKeyType = UIReturnKeyDone;
    URLValue.clearButtonMode = UITextFieldViewModeNever;
    URLValue.autocapitalizationType = UITextAutocapitalizationTypeNone;
    URLValue.textColor = funBlue;
    URLValue.contentVerticalAlignment =  UIControlContentVerticalAlignmentCenter;
    [URLValue addTarget:self action:@selector(URLValueEditedAction:) forControlEvents:UIControlEventEditingDidEnd];
    [URLParameter addSubview:URLValue];

    usernameParameter = [[UITableViewCell alloc] init];
    [[usernameParameter textLabel] setText:NSLocalizedString(@"Username",@"Username")];
    [usernameParameter setSelectionStyle:UITableViewCellSelectionStyleNone];
    usernameValue = [[UITextField alloc] initWithFrame:CGRectMake(115.0, 3.0, 185.0, 40)];
    usernameValue.borderStyle = UITextBorderStyleNone;
    usernameValue.contentVerticalAlignment =  UIControlContentVerticalAlignmentCenter;
    //usernameValue.textAlignment = UITextAlignmentRight;
    usernameValue.font = small_font;
    if([username isEqualToString:@""]||[username isEqualToString:@"guest "]){
        usernameValue.placeholder = @"username";
        //usernameValue.text = username;
    }else{
        usernameValue.text = username;
    }
    usernameValue.backgroundColor = [UIColor whiteColor];    
    usernameValue.keyboardType = UIKeyboardTypeEmailAddress;
    usernameValue.returnKeyType = UIReturnKeyDone;
    usernameValue.autocorrectionType = UITextAutocorrectionTypeNo;
    usernameValue.textColor = funBlue;
    usernameValue.clearButtonMode = UITextFieldViewModeNever;
    usernameValue.autocapitalizationType = UITextAutocapitalizationTypeNone;
    [usernameValue addTarget:self action:@selector(usernameValueEditedAction:) forControlEvents:UIControlEventAllEditingEvents];
    [usernameParameter addSubview:usernameValue];
    
    passwordParameter = [[UITableViewCell alloc] init];
    [passwordParameter setSelectionStyle:UITableViewCellSelectionStyleNone];
    [[passwordParameter textLabel] setText:NSLocalizedString(@"Password",@"Password")];
    passwordValue = [[UITextField alloc] initWithFrame:CGRectMake(115.0, 3.0, 185.0, 40)];
    passwordValue.borderStyle = UITextBorderStyleNone;
    passwordValue.contentVerticalAlignment =  UIControlContentVerticalAlignmentCenter;
    //passwordValue.textAlignment = UITextAlignmentRight;
    passwordValue.textColor = funBlue;
    passwordValue.font = small_font;
    if([password isEqualToString:@""]){
        passwordValue.placeholder = @"password";
    }else {
        passwordValue.text = password;
    }
    //[passwordValue  setEditing:TRUE];
    passwordValue.backgroundColor = [UIColor whiteColor];
    passwordValue.autocorrectionType = UITextAutocorrectionTypeNo;
    passwordValue.keyboardType = UIKeyboardTypeDefault;
    passwordValue.returnKeyType = UIReturnKeyDone;
    passwordValue.clearButtonMode = UITextFieldViewModeNever;
    passwordValue.secureTextEntry = YES;
    [passwordValue addTarget:self action:@selector(passwordValueEditedAction:) forControlEvents:UIControlEventAllEditingEvents];
    [passwordParameter addSubview:passwordValue]; 

    
    [self.view addSubview:accountTable];

    [accountTable reloadData];

}

- (void) viewDidAppear:(BOOL) animated{
    
    [[FunambolAPI getInstance] loadSyncConfig:&URL username:&username password:&password];
    if([username isEqualToString:@""]||[password isEqualToString:@""]){
        [self noCredsAlert:NSLocalizedString(@"emptyCreds", @"emptyCreds")];
    }
    StringBuffer urlstring([URL UTF8String]);
    if((urlstring.find(" ") != StringBuffer::npos)||
       (urlstring.find("<") != StringBuffer::npos)||
       (urlstring.find(">") != StringBuffer::npos)){
        [self noCredsAlert:NSLocalizedString(@"wrongUrl", @"wrongUrl")];
    } 
}

- (void) viewWillDisappear:(BOOL) animated{
}

- (void) reload {

}

- (UITableViewCell *)tableView:(UITableView *)accountTable cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([self isPortal]){
        switch (indexPath.row) {
            case 0:
                return usernameParameter;
            case 1:
                return passwordParameter;
            default:
                break;
        }
    }else{
        
        switch (indexPath.row) {
            case 0:
                return URLParameter;
            case 1:
                return usernameParameter;
            case 2:
                return passwordParameter;
            default:
                break;
        }
    }
    return nil;
}

- (NSInteger)tableView:(UITableView *)accountTable numberOfRowsInSection:(NSInteger)section {
    if([self isPortal]){
        return 2;
    }else{
        return 3;
    }
}

- (CGFloat)tableView:(UITableView *)accountTable heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section) {

        default:
            return 45;
            break;
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)accountTable {
    return 1;
}

- (BOOL) isPortal{
    return FALSE;
}

- (void)URLValueEditedAction:(id)sender
{
    StringBuffer val;
    val = [URLValue.text UTF8String];
    val.replaceAll("%", "");
    [URLValue setText:[[NSString alloc] initWithUTF8String:val.c_str()]];
    [[FunambolAPI getInstance] saveURLConfig:URLValue.text];
}

- (void)usernameValueEditedAction:(id)sender
{
    if([usernameValue.text isEqualToString:@""]){
        usernameValue.placeholder = @"username";
    }else{
    
    }
    
    [[FunambolAPI getInstance] saveUsernameConfig:usernameValue.text];
}

- (void)passwordValueEditedAction:(id)sender
{
    if([passwordValue.text isEqualToString:@""]){
        passwordValue.placeholder = @"password";
    }else{
    }
    
    [[FunambolAPI getInstance] savePasswordConfig:passwordValue.text];
}

- (void)dealloc {
    // TODO dealloc all items
    [accountTable release];
    
    [URLValue release];
    [usernameValue release];
    [passwordValue release];
    
    [URLParameter release];
    [usernameParameter release];
    [passwordParameter release];
    
    [small_font release];
    
    [URL release];
    
    
    [funBlue release];
    [username release];
    [password release];
    [super dealloc];
}



@end
